/**
 * 
 */
package com.rangers.manage.email.handler;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

@Component
public class EmailSendTask {

	public static BlockingQueue<Map<JavaMailSender, MimeMessage>> msgQueue = new LinkedBlockingDeque<>(1000);

	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	private static final Logger log = LoggerFactory.getLogger(EmailSendTask.class);

	public static void addToQueue(Map<JavaMailSender, MimeMessage> target) {
		try {
			msgQueue.put(target);
		} catch (InterruptedException e) {
			log.error("向邮件队列中添加发送任务：failed -> {}", e.getMessage());
			throw new RuntimeException("邮件发送失败");
		}
	}

	public void doSendTask() {
		while (msgQueue.size()>0) {
			threadPoolTaskExecutor.submit(() -> {
				try {
					Map<JavaMailSender, MimeMessage> take = msgQueue.take();
					if (take != null && !take.isEmpty()) {
						take.forEach((k, v) -> {
							k.send(v);
							log.info("从邮件队列中执行发送任务:start -> content:{}--{}", k.toString(), v.toString());
						});
					}
				} catch (InterruptedException e) {
					log.error("从邮件队列中执行发送任务：failed -> {}", e.getMessage());
					throw new RuntimeException("邮件发送失败");
				}

			});
		}
	}
}
